<?php

namespace App\Http\Middleware\Api;

use Closure;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class LoginCheck extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try{
            if (!$this -> auth -> parser() -> setRequest($request) -> hasToken()) {
                throw new \Exception('token不能为空');
            }

            // !$this -> auth -> parseToken() -> check()
            // !$this->auth->parseToken()->authenticate()
            // JWTAuth::parseToken()->check()
            if (!Auth::guard('api') -> check()) {
                throw new \Exception('token无效或已过期');
            }

            return $next($request);

        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }


//        // 检查此次请求中是否带有 token，如果没有则抛出异常。
//        $this -> checkForToken($request);
//        try {
//            // 检测用户的登录状态，如果正常则通过
//            if (!Auth::guard('api') -> check()) {
//                throw new \Exception('token无效或已过期');
//            }
//            return $next($request);
//
//        } catch (\Exception $e) {
//            return response() -> json(['error_code' => 400,'msg' => $e -> getMessage()]);
//        }

    }
}
